#include "server_command.h"


CmdHash *init_cmdHash()
{
    CmdHash *table = (CmdHash *)calloc(1, sizeof(CmdHash));
    
    // 遍历保存命令全部信息的静态数组
    // 将信息保存到哈希表中
    for (int i = 0; i < CMD_MAX; i++) {
        int index = hash(cmd[i].cmdString);
        // 保存信息到哈希表，使用头插法
        //
        // 初始化结点
        Cmd_t *newNode = (Cmd_t *)calloc(1, sizeof(Cmd_t));
        newNode->cmdCode = cmd[i].cmdCode;
        newNode->cmdString = cmd[i].cmdString;
        // 插入
        newNode->next = table->CmdTable[index];
        table->CmdTable[index] = newNode;
    }

    return table;
}

// 哈希函数
int hash(char *key) 
{
    int h = 0, g;
    while (*key) {
        h = (h << 4) + *key++;
        g = h & 0xf0000000;
        if (g)
            h ^= g >> 24;
        h &= ~g;
    }
    return h % CMDHASHTABLELEN;
}


// 根据cmdstring得到命令对应的宏
int get_cmdcode(char *cmdString)
{
#ifndef table
    // 初始化哈希表
    CmdHash *table = init_cmdHash();
#endif
    // 根据字符串得到索引
    int index = hash(cmdString);
    // 遍历当前索引的哈希位置
    for (Cmd_t *current = table->CmdTable[index]; current != NULL; current = current->next) {
        if (strcmp(current->cmdString, cmdString) == 0) {
            return current->cmdCode;
        }
    }
    return -1;
}

// 解析命令、执行命令
void handle_server_cmd(const char *buf, int fd) 
{
    // 得到命令字符串
    char cmdString[10] = {0};
    sscanf(buf, "%s", cmdString);
    // 根据命令字符串得到命令的宏
    int cmdCode = get_cmdcode(cmdString);
    // 根据不同的命令执行不同的接口
    switch (cmdCode) {
    case CMD_CD:
        printf("cd work\n");
        break;
    case CMD_LS:
        printf("ls work\n");
        break;
    case CMD_PWD:
        printf("pwd work\n");
        break;
    case CMD_PUTS:
        printf("puts work\n");
        break;
    case CMD_GETS:
        printf("gets work\n");
        break;
    case CMD_RM:
        printf("rm work\n");
        break;
    case CMD_MKDIR:
        printf("mkdir work\n");
        break;
    }
}
